<script setup>
const user = computed(() => {
  return JSON.parse(localStorage.getItem('user'));
});
import {computed, ref} from 'vue';
import axios from 'axios';
import { ElForm, ElFormItem, ElInput, ElMessage, ElButton } from 'element-plus';
let formData = ref({
      loginname: '',
      uname: '',
      pwd: '',
      sex:'',
      uimage: '',
      email: '',
      tel: '',
      se3:''
    })
const originalPhone = user.value.tel; // 假设这是用户的原始手机号
const dialogVisible = ref(false);
const form = ref({
    phone: "",
    newPassword: "",
    confirmPassword: "",
});
function updatepassword(){
    form.value ={
        phone: "",
        newPassword: "",
        confirmPassword: "",
    };
    // 重置表单
    dialogVisible.value=true

}
const rules = {
    phone: [
        { required: true, message: "手机号不能为空", trigger: "blur" },
        {
            pattern: /^[1][3-9][0-9]{9}$/,
            message: "请输入有效的手机号",
            trigger: "blur",
        },
        {
            validator: (rule, value, callback) => {
                if (value !== originalPhone) {
                    callback(new Error("手机号与原手机号不一致"));
                } else {
                    callback();
                }
            },
            trigger: "blur",
        },
    ],
    newPassword: [
        { required: true, message: "新密码不能为空", trigger: "blur" },
        {
            pattern: /^\d{6}$/,
            message: "密码必须是6位数字",
            trigger: "blur",
        },
    ],
    confirmPassword: [
        { required: true, message: "确认密码不能为空", trigger: "blur" },
        {
            validator: (rule, value, callback) => {
                if (value !== form.value.newPassword) {
                    callback(new Error("两次密码不一致"));
                } else {
                    callback();
                }
            },
            trigger: "blur",
        },
    ],
};



// function openDialog() {
//     dialogVisible.value = true;
// }
function submitForm() {


    if(form.value.phone!=="" && form.value.newPassword!=="" && form.value.confirmPassword!=="") {
        axios({
            url:"http://localhost:8080/user/changePwd",
            method:"post",
            data:{
                "password":form.value.newPassword,
                "uid":user.value.uid
            },
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded' // 设置正确的请求头
            }
        }).then((response) => {
            if(response.data===1){
                // error
                ElMessage({
                    type: 'success',
                    message: '修改成功',
                    showClose: true
                });
                dialogVisible.value =false;
                initUserData();
            }else{
                // success

                ElMessage({
                    type: 'error',
                    message: '修改失败',
                    showClose: true
                });
            }
            dialogVisible.value =false;
            initUserData();
        }).catch((error) => {
            console.error('查询失败:', error);
            ElMessage.error('查询失败');

        });
    }

}
initUserData();
// 页面初始化时获取用户数据
function initUserData() {
  axios.get('http://localhost:8080/user/upUser', { params: { uid: user.value.uid } })
      .then(response => {
        formData.value = response.data;
      })
      .catch(error => {
        console.error('Error fetching user data:', error);
      });
}

// 验证邮箱格式
function validateEmail(email) {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

// 验证电话号码格式
function validateTel(tel) {
  const telRegex = /^\d{11}$/;
  return telRegex.test(tel);
}

function updateuser(){
  if (!formData.value.uname ||!formData.value.email ||!formData.value.tel || (formData.value.sex!== '男' && formData.value.sex!== '女') ||!validateEmail(formData.value.email) ||!validateTel(formData.value.tel)) {
    ElMessage({
      message: '请输入合法的用户姓名、邮箱和联系电话',
      type: 'warning',
      showClose: true,
    });
    return;
  }
  axios({
    url:"http://localhost:8080/user/updateUser",
    method:"post",
    data:formData.value,
  }).then((response)=>{
    if(response.data===1){
      initUserData();
      ElMessage({
        message: '修改成功',
        type: 'success',
        showClose: true,
      })
    }else{
      initUserData();
      ElMessage({
        message: '修改失败',
        type: 'error',
        showClose: true,
      })
    }
  })
}

// 定义响应式数据来存储文件
const selectedFile = ref(null);

// onFileChange 方法用于更新 selectedFile 的值
const onFileChange = (event) => {
  selectedFile.value = event.target.files[0];
};

// submitForms 方法用于处理表单提交
const submitForms = async (event) => {
  event.preventDefault(); // 阻止表单默认提交行为

  if (!selectedFile.value) {
    alert('请选择文件');
    return;
  }

  // 创建 FormData 对象并添加文件
  const formDatas = new FormData();
  formDatas.append('file', selectedFile.value);

  try {
    // 发送 POST 请求到服务器
    const response = await fetch('http://localhost:8080/user/image', {
      method: 'POST',
      body: formDatas,
    });

    // 检查响应状态
    if (response.ok) {
      const data = await response.json();
      const filename = data.filename;
    }

    // 处理响应数据
    // const data = await response.json();
    // console.log(data);
  } catch (error) {
  }
};

</script>

<template>
  <div>
    <h2 style="margin-bottom: 30px">个人信息</h2>
    <el-form :model="formData" label-width="120px">
      <el-form-item label="头像">
        <form @submit.prevent="submitForms" enctype="multipart/form-data">
          <input type="file" name="file" @change="onFileChange">
          <input type="submit" value="提交">
        </form>

          <div>
              <el-button type="primary" @click="updatepassword()">修改密码</el-button>
              <el-dialog v-model="dialogVisible" title="修改密码">
                  <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                      <!-- 手机号 -->
                      <el-form-item label="手机号" prop="phone" style="margin-bottom: 15px">
                          <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
                      </el-form-item>

                      <!-- 新密码 -->
                      <el-form-item label="新密码" prop="newPassword" style="margin-bottom: 15px">
                          <el-input
                                  type="password"
                                  v-model="form.newPassword"
                                  placeholder="请输入新密码"
                          ></el-input>
                      </el-form-item>

                      <!-- 确认密码 -->
                      <el-form-item label="确认密码" prop="confirmPassword" style="margin-bottom: 15px">
                          <el-input
                                  type="password"
                                  v-model="form.confirmPassword"
                                  placeholder="请再次输入密码"
                          ></el-input>
                      </el-form-item>
                  </el-form>

                  <div slot="footer" class="dialog-footer">
                      <el-button @click="dialogVisible = false">取消</el-button>
                      <el-button type="primary" @click="submitForm">提交</el-button>
                  </div>
              </el-dialog>
          </div>

      </el-form-item>
      <el-form-item label="用户账号">
        <el-input v-model="formData.loginname" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户姓名">
        <el-input v-model="formData.uname"></el-input>
      </el-form-item>
      <el-form-item label="地址">
        <el-input v-model="formData.se3"></el-input>
      </el-form-item>
<!--      <el-form-item label="密码">-->
<!--        <el-input v-model="formData.pwd" show-password></el-input>-->
<!--      </el-form-item>-->
      <el-form-item label="性别">
        <el-radio-group v-model="formData.sex">
          <el-radio value="男">男</el-radio>
          <el-radio value="女">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="formData.email"></el-input>
      </el-form-item>
      <el-form-item label="联系电话">
        <el-input v-model="formData.tel"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button color="#EFE154" @click="updateuser">保存修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>

</style>